package com.nathan.crm.controller;

import com.nathan.base.BaseController;
import com.nathan.crm.service.PermissionService;
import com.nathan.crm.service.UserService;
import com.nathan.crm.utils.LoginUserUtil;
import com.nathan.crm.vo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class IndexController extends BaseController {

    @Autowired
    private UserService userService;
    @Autowired
    private PermissionService permissionService;

    @RequestMapping("/")
    public String toMain(HttpServletRequest request){
        return main(request);
    }

    /**
     * 系统登录页
     * @return
     */
    @RequestMapping("index")
    public String index(){
        return "index";
    }

    /**
     * 系统欢迎页
     * @return
     */
    @RequestMapping("welcome")
    public String welcome(){
        return "welcome";
    }

    /**
     * 后端管理主页
     * @param request
     * @return
     */
    @RequestMapping("/main")
    public String main(HttpServletRequest request){
        // 获取Cookie中的用户id
        int id = LoginUserUtil.releaseUserIdFromCookie(request);

        // 查询用户对象，设置session作用域
        User user = userService.selectByPrimaryKey(id);
        request.getSession().setAttribute("user",user);

        // 通过用户id查询其对应的所拥有的资源权限列表（资源授权码）
        List<String> permissions = permissionService.countUserHasPermissionByUserId(id);
        // 将用户所拥有的资源权限授权码集合存入session对象中
        if (permissions.size() > 0) {
            request.getSession().setAttribute("permissions",permissions);
        }

        return "main";
    }
}
